#include <QtGui>
#include <QtNetwork>
#include <QtXml>
#include "src/serverexplorerimpl.h"
#include "ui_serverexplorer.h"

ServerExplorerImpl::ServerExplorerImpl(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::ServerExplorerImpl)
{
    m_ui->setupUi(this);
    m_ui->serverPortLineEdit->setValidator(new QIntValidator( 1, 65535, this) );
    this->serverInfo_ui = new ServerInfo();
    this->tcpSocket = new QTcpSocket();
    serverInfoPort_ = 8080;
    NickName = "Newbie";
    connect( m_ui->checkButton, SIGNAL(clicked()), this, SLOT(ConnectToServer()) );
    connect( m_ui->nickNameButton, SIGNAL(clicked()), this, SLOT(SetNickName()) );

    connect( this->tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SLOT(displayError(QAbstractSocket::SocketError)) );
    connect( this->tcpSocket, SIGNAL(connected()), this, SLOT(ServerConnected()) );
}

ServerExplorerImpl::~ServerExplorerImpl()
{
    delete m_ui;
}

void ServerExplorerImpl::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ServerExplorerImpl::ConnectToServer()
{
    this->tcpSocket->abort();
    this->tcpSocket->connectToHost( m_ui->serverAddressLineEdit->text(),
                                   m_ui->serverPortLineEdit->text().toInt() );



}

void ServerExplorerImpl::ServerConnected()
{
    m_ui->serverInfoButton->setEnabled(true);
    connect( this->tcpSocket, SIGNAL(readyRead()), this, SLOT(ReadFromServer()) );
    connect( this->tcpSocket, SIGNAL(readyRead()), this, SLOT(SendNickName()) );
    connect( this->m_ui->serverInfoButton, SIGNAL(clicked()), this, SLOT(ShowServerInfo()) );

}

void ServerExplorerImpl::ReadFromServer()
{
    ParseXML(tcpSocket->readAll() );

}

void ServerExplorerImpl::displayError(QAbstractSocket::SocketError socketError)
{
    QString msg;
    switch(socketError)
    {
        case QAbstractSocket::RemoteHostClosedError:
            break;
        case QAbstractSocket::HostNotFoundError:
            msg.append("Host not found");
            break;
        case QAbstractSocket::ConnectionRefusedError:
            msg.append("Connection Refused");
            break;
        default:
            msg.append("Failure: ").append(this->tcpSocket->errorString() );
    }
    if( !msg.isEmpty() )
        QMessageBox::information(this, "Server Error", msg);
}

void ServerExplorerImpl::ShowServerInfo()
{
    this->serverInfo_ui->serverAddress = m_ui->serverAddressLineEdit->text();
    this->serverInfo_ui->serverPort = this->serverInfoPort_;
    this->serverInfo_ui->Load();
    this->serverInfo_ui->exec();
}

void ServerExplorerImpl::SetNickName()
{
    NickName = this->m_ui->nickNameLineEdit->text();
}

void ServerExplorerImpl::SendNickName()
{
    QString msg;
    msg.append("<NickName>").append(NickName).append("</NickName>");
    QByteArray block;
    block.append(msg.toUtf8());
    this->tcpSocket->write(block);
    this->tcpSocket->flush();
}

void ServerExplorerImpl::ParseXML(QString xmlstring)
{
    this->serverInfo_ui->setWindowTitle(xmlstring);
    QString element;

    if(Get(element, xmlstring, QString("ServerName")) )
        m_ui->serverNameLineEdit->setText(element);
    if(Get(element, xmlstring, QString("ServerInfoPort")) )
        this->serverInfoPort_ = element.toInt();
    if(Get(element, xmlstring, QString("ServerLevel")) )
        m_ui->levelLineEdit->setText(element);
}

bool ServerExplorerImpl::Get(QString &string, QString &source, QString NodeName)
{
    QDomDocument domDocument;
    domDocument.setContent(source);
    QDomElement root;
    root = domDocument.documentElement();
    if ( root.tagName() != "ServerInfo" )
        return false;
    //QDomElement domElement;
    //domElement = domDocument.firstChildElement(NodeName);
    QDomNodeList domNode;
    domNode = root.elementsByTagName(NodeName);
    //QDomElement domElement = domDocument.elementsByTagName(NodeName).item(1).toElement();
    QDomElement domElement;
    for( int i=0; i< domNode.length(); i++)
    {
        domElement = domNode.at(i).toElement();
    }
    if(domElement.isNull())
        return false;
    string = domElement.text();
    return true;
}
